<?php

namespace App\Http\Middleware;

use Closure;
use App\Model\AdminUserModel;

class AdminRoleMiddleware
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        // 判断是否已经登录 末登录跳转到首页
        if (empty(session('Adminuser-data'))) {
            return redirect()->route('Admin.login')->with('message', '请先登录');
        }

        $user = session('Adminuser-data');
        // 收集放行角色列表
        $role = [];
        for ($i=2; $i < func_num_args(); $i++) {
            $role[] = func_get_arg($i);
        }

        // 判断你是否有权限
        // 获取用户的角色数组
        $user_roles = [];
        foreach (AdminUserModel::find($user['id'])->roles->toArray() as $value) {
            $user_roles[] = $value['name'];
        }

        // 用数组的方式来求交集
        if (!array_intersect($role, $user_roles)) {
            return redirect()->route('Admin.index')->with('message','你没有权限执行该操作');
        }
        //dd($user_roles);

        return $next($request);
    }
}
